#include "SampleUploader.h"



bool SampleUploader::collectPostData() {
	data.appendTextField("a", "upload");
	return true;
}


bool SampleUploader::appendImageToPost(const ImageToUpload &image)
{
	data.appendBinaryField("file[]", image.ImageName, image.mimeType, image.Image->readAll());
	return true;
}

bool SampleUploader::setHeaders(QNetworkRequest &req) {
	req.setRawHeader("Accept-Encoding", "plain"); // Remove it after debug
	req.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + data.getBoundary());
	return true;
}

static QStringList getAllMatches(QRegExp &rx, const QString &string) {
	QStringList ret;
	rx.setMinimal(true);
	if (string.contains(rx)) {
		int pos = 0;
		while ((pos = rx.indexIn(string, pos)) != -1) {
			ret << rx.cap(1);
			pos += rx.matchedLength();
		}
	}
	return ret;
}


QList<UploadResult> SampleUploader::parseResponse() const {
	reply->seek(0);
	QList<UploadResult> ret;
	QString html = reply->readAll();
	QRegExp tableRX("<table\\s+class=\"links\"\\s+cellspacing=\"3\">(.*)</table>");
	QStringList tables = getAllMatches(tableRX, html);
	int counter = 0;
	foreach (QString table, tables) {
		UploadResult res = parseResponseSingle(table);
		res.index = this->images.at(counter++).index;
		ret.append(res);
		qDebug() << counter<< res.index << res.ImageName << res.success;
		if ( counter >= images.size() )
			break;
	}
	return ret;
}

static void parseCells(const QStringList &tds, UploadResult &links);

UploadResult SampleUploader::parseResponseSingle(const QString &table) const {
	UploadResult links;
	QRegExp thRX("<th colspan=\"3\">(.*)</th>");
	QStringList ths = getAllMatches(thRX, table);
	// parse TH here
	if ( ths.size() == 1 )
		links.ImageName = ths.first();
	else if (ths.size() > 1)
		qWarning() << __FUNCTION__ << "looks like it's time to fix parser";

	QRegExp trRX("<tr>(.*)</tr>");
	QStringList trs = getAllMatches(trRX, table);
	foreach (QString tr, trs) {
		QRegExp tdRX("(<td .*</td>)");
		// UploadResult links filled here
		parseCells(getAllMatches(tdRX, tr), links);
	}
	qDebug() << __FUNCTION__ << __LINE__ << links.success << links.errorString;
	if ( links.success )
		checkLinks(links);
	qDebug() << "finish parsing. success:" << links.success;
	return links;
}

enum Keys { // All that we can find is
	nothing,
	thumb_link,
	html_link,
	image_link,
	error_message
};

static bool tryFind(const QString &line, Keys foundKey, UploadResult &links);
static QString tryFind(const QString &line, const QRegExp &pattern);

static void parseCells(const QStringList &tds, UploadResult &links) {
	Keys foundKey = nothing;
	foreach (QString td, tds) {
		if ( td.contains("<b>Error:</b>") ) {
			foundKey = error_message;
			qDebug() << "looking for error string";
		}
		else if ( td.contains(QRegExp("a target=\"_blank\" href=\".*img src=\".*</a>")) )
			continue;
		else if ( td.contains("Forum Thumbnail Link") ) {
			foundKey = thumb_link;
			continue;
		}
		else if ( td.contains("Text Link") ) {
			foundKey = html_link;
			continue;
		}
		else if ( td.contains("Hotlink") ) {
			foundKey = image_link;
			continue;
		}
		if ( foundKey != nothing ) {
			if ( tryFind(td, foundKey, links) ) {
				if ( foundKey == error_message ) {
					links.success = false;
					qDebug() << __FUNCTION__ << __LINE__ << links.success << links.errorString;
					return;
				}
				foundKey = nothing;
			}
		}
	}
}

static bool tryFind(const QString &line, Keys foundKey, UploadResult &links)
{
	switch (foundKey) {
		case thumb_link:
			links.Thumb = tryFind(line, QRegExp("(http://\\w*\\.imagehost\\.org/t/[^[]+)"));
			return !links.Thumb.isEmpty();
		case html_link:
			links.ImageHtml = tryFind(line, QRegExp("(http://\\w*\\.imagehost\\.org/view/[^\"]+)"));
			return !links.ImageHtml.isEmpty();
		case image_link:
			links.Image = tryFind(line, QRegExp("value=\"(http://\\w*\\.imagehost\\.org/[^\"]+)\""));
			return !links.Image.isEmpty();
		case error_message:
			links.errorString = tryFind(line, QRegExp("<td class=\"error\">(.*)</td>"));
			qDebug() << "looked for error string" << links.errorString;
			return !links.errorString.isEmpty();
		default:
			return false;
	}
	return false;
}

static QString tryFind(const QString &line, const QRegExp &pattern)
{
	QString ret;
	int pos = pattern.indexIn(line);
	if (pos > -1)
		return pattern.cap(1);
	return QString::null;
}

bool SampleUploader::checkLinks(UploadResult &links) const
{
	qDebug() << "checkLinks:" << links.Image << links.ImageHtml << links.success;
	QSettings Config;
	if ( links.Image.isEmpty() and links.ImageHtml.isEmpty() ) {
		qWarning() << "neither hotlink nor html link are present";
		links.errorString = tr("Check links failed. Some Links absent. Probably server gave unparsible answer");
		links.success = false;
		return false;
	}
	if ( links.Image.isEmpty() and Config.value("useHtml", true).toBool() ) {
		links.Image = links.ImageHtml;
		qDebug() << "Image" << links.Image;
	}
	if ( links.ImageHtml.isEmpty() and Config.value("useHotlink", true).toBool() ) {
		links.ImageHtml = links.Image;
		qDebug() << "ImageHtml" << links.ImageHtml;
	}
	if ( links.Thumb.isEmpty() and Config.value("useImageName", true).toBool() ) {
		links.Thumb = links.ImageName;
		qDebug() << "Thumb" << links.Thumb;
	}
	qDebug() << "Image:" << links.ImageName;
	links.success = true;
	return true;
}



